#include "NetworkServer.h"

#include <iostream>

void *runServer(void *serverHandler){
	NetworkServer *server = (NetworkServer*)serverHandler;
	server->awaitConnections();
}

NetworkServer::NetworkServer(int maxConnections, int portNumber){
	port = portNumber;
	maxCons = maxConnections;
	
	if( SDLNet_ResolveHost(&ip, NULL, portNumber)==-1 ){exit(1);}
	serverSocket = SDLNet_TCP_Open(&ip);
	if(!serverSocket){exit(1);}
	
	serverSS = SDLNet_AllocSocketSet(1);
	SDLNet_TCP_AddSocket(serverSS, serverSocket);
	
	pthread_create( &serverThread, NULL, runServer, this );
	
	std::cout << "Making Server\n";
}

NetworkServer::~NetworkServer(){
	live = 0;
	pthread_join( serverThread, NULL );
}

int NetworkServer::getNumberOfConnections(){
	int toRet;
	
	pthread_mutex_lock( &connectionLock );
	toRet = numConnections;
	pthread_mutex_unlock( &connectionLock );
	
	return numConnections;
}

void NetworkServer::awaitConnections(){
	while(live){
		int numready = SDLNet_CheckSockets(serverSS, TIMEOUT);
		if(numready == -1){exit(1);}
		
		pthread_mutex_lock( &connectionLock );
		
		if(numready){
			if( SDLNet_SocketReady(serverSocket) ){
				if(numConnections < maxCons){
					connections[numConnections] = SDLNet_TCP_Accept(serverSocket);
					if(!(connections[numConnections])){exit(1);}
					std::cout << "Player Found\n";
					addInputHandler(numConnections);
					numConnections++;
				}
			}
		}
		
		pthread_mutex_unlock( &connectionLock );
		
		//std::cout << "S\n";
		pthread_yield();
	}
}

